﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Steve.UI.Administration.Models;
using AutoMapper;
using System.ComponentModel.Composition;

namespace Steve.UI.Administration.Controllers
{
    public class SiteManagementControllerBase : Controller
    {
        [Import]
        public SiteExplorerRepository Repository { get; set; }

        public virtual ActionResult SiteList()
        {
            var sites = Repository.GetSites();

            return View("SiteList", sites);
        }

        public virtual ActionResult SiteDetail(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                var model = new NewSiteDetailModel();

                return View("NewSiteDetail", model);
            }
            else
            {
                var model = new ExistingSiteDetailModel();

                var site = Repository.GetSite(id);

                Mapper.Map(site, (ExistingSiteDetailModel) model);

                return View("ExistingSiteDetail", model);
            }
        }

        [ActionName("SiteDetail")]
        [HttpPost]
        [RouteValueAbsent("id")]
        public virtual ActionResult SiteDetailPost(NewSiteDetailModel model)
        {
            if (!ModelState.IsValid)
            {
                return View("NewSiteDetail", model);
            }

            var site = new Site();

            Mapper.Map(model, site);

            Repository.SaveSite(site);

            return RedirectToAction("SiteList", "SiteManagement");
        }

        [ActionName("SiteDetail")]
        [HttpPost]
        [RouteValuePresent("id")]
        public virtual ActionResult SiteDetailPost(ExistingSiteDetailModel model, string id)
        {
            if (!ModelState.IsValid)
            {
                return View("ExistingSiteDetail", model);
            }

            var site = new Site();

            Mapper.Map(model, site);

            site.SiteName = id;

            Repository.SaveSite(site);

            return RedirectToAction("SiteList", "SiteManagement");
        }

        public virtual ActionResult NewAlternate()
        {
            var model = string.Empty;

            return View("NewAlternate", model);
        }
    }
}
